﻿using System.Web.Mvc;
using GdNet.Web.Mvc;
using GdNet.WebFramework.Business.System;
using GdNet.WebFramework.Domain.System;
using GdNet.WebFramework.Modules.Common;
using GdNet.WebFramework.Modules.Common.Assistants;
using GdNet.WebFramework.Modules.Common.ModuleBase;

namespace GdNet.WebFramework.Gui.Controllers
{
    public class AdminController : AbstractController
    {
        private ActionDetail _actionDetail;
        private ModuleAction _moduleAction;
        private IModuleActionService _moduleActionService;
        private readonly IModuleService _moduleService;

        public AdminController(IModuleService moduleService)
        {
            _moduleService = moduleService;
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            this.LoadModuleAction();
        }

        public ActionResult Index()
        {
            var result = _moduleActionService.Execute(_actionDetail);
            return View(this.BuildPageDetailModel(result));
        }

        [HttpPost]
        public ActionResult Index(FormCollection formCollection)
        {
            var result = ((IModuleActionPostbackService)_moduleActionService).Submit(_actionDetail, formCollection);
            if (result)
            {
                return RedirectToAction("Index", new { m = "cms", a = "al" });
            }

            return View(this.BuildPageDetailModel(null));
        }

        private void LoadModuleAction()
        {
            _actionDetail = ActionAssistant.Parse(base.Request);
            _moduleAction = _moduleService.GetModuleAction(_actionDetail.ModuleCode, _actionDetail.ActionCode);
            _moduleActionService = ActionAssistant.LoadActionService(_moduleAction);
        }

        private PageDetailModel BuildPageDetailModel(object result)
        {
            return new PageDetailModel()
            {
                Title = _moduleAction.Name,
                Header = _moduleAction.Name,
                PartialView = _moduleActionService.GetViewPath(_actionDetail.ModuleCode, _moduleAction.ViewName),
                Result = result,
            };
        }
    }
}
